package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.novel.domain.Integral;
import com.ruoyi.novel.domain.Order;
import com.ruoyi.novel.domain.User;
import com.ruoyi.novel.domain.Vip;
import com.ruoyi.novel.service.IOrderService;
import com.ruoyi.novel.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单相关接口
 */

@RestController
@RequestMapping("/app/order")
public class AppOrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserService userService;

    /**
     * 创建订单
     * @param order
     * @return
     */
    @PostMapping("/createOrder")
    public AjaxResult createOrder(@RequestBody Order order){
        order.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        //测试用
        order.setType(0);
        order.setState(0);
        AjaxResult result = orderService.createOrder(order);
        callbackOrder(order, result);
        return result;
    }

    @Transactional
    public void callbackOrder(Order order, AjaxResult result){
        User user = userService.getById(SecurityUtils.getUserId());
        if(order.getMode() == 0){
            //会员订单
            Vip vip = (Vip) result.get("vip");
            if(vip != null){
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", user.getId()).set("level",vip.getLevel());
                if(vip.getLevel() == 10){
                    updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 DAY)");
                }else if(vip.getLevel() == 20){
                    updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 MONTH)");
                }else if(vip.getLevel() == 30){
                    updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 YEAR)");
                }else if(vip.getLevel() == 90){
                    updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 99 YEAR)");
                }
                userService.update(updateWrapper);
            }
        }else if(order.getMode() == 1){
            //充值订单
            Integral integral = (Integral) result.get("integral");
            if(integral != null){
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", user.getId()).setSql("money = money +"+ integral.getIntegral());
                userService.update(updateWrapper);
            }
        }
    }
}
